package com.vimi8.chick.plugins.event;

import android.Manifest;
import android.content.Context;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.util.Base64;

import com.eros.framework.manager.ManagerFactory;
import com.eros.framework.manager.impl.ParseManager;
import com.eros.framework.manager.impl.PersistentManager;
import com.eros.framework.manager.impl.dispatcher.DispatchEventManager;
import com.eros.framework.model.UploadImageBean;
import com.eros.framework.model.UploadResultBean;
import com.eros.framework.model.WeexEventBean;
import com.eros.framework.utils.JsPoster;
import com.eros.framework.utils.PermissionUtils;
import com.eros.wxbase.EventGate;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.journeyapps.barcodescanner.BarcodeEncoder;
import com.squareup.otto.Subscribe;
import com.taobao.weex.bridge.JSCallback;
import com.vimi8.chick.plugins.constant.Constant;
import com.vimi8.chick.plugins.constant.EventCenter;
import com.vimi8.chick.plugins.manager.PictureManager;
import com.vimi8.chick.plugins.model.PictureBean;
import com.vimi8.chick.plugins.model.QrcodeBean;
import com.vimi8.chick.plugins.model.VideoBean;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class EventPicture extends EventGate {
    private JSCallback mPickCallback;

    @Override
    public void perform(Context context, WeexEventBean weexEventBean, String type) {
        String params = weexEventBean.getJsParams();
        if (EventCenter.EVENT_PICTURE_PICK.equals(type)) {
            pick(params, context, weexEventBean.getJscallback());
        } else if (EventCenter.EVENT_PICTURE_QRCODE.equals(type)) {
            qrcode(params, context, weexEventBean.getJscallback());
        } else if (EventCenter.EVENT_PICTURE_VIDEO.equals(type)) {
            video(params, context, weexEventBean.getJscallback());
        } else if (EventCenter.EVENT_PICTURE_PREVIEW.equals(type)) {
            videoPreview(params, context, weexEventBean.getJscallback());
        }
    }

    public void pick(String json, Context context, JSCallback jsCallback) {
        if (!PermissionUtils.checkPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE)) {
            return;
        }
        mPickCallback = jsCallback;
        PictureBean bean = ManagerFactory.getManagerService(ParseManager.class).parseObject(json, PictureBean.class);
        ManagerFactory.getManagerService(DispatchEventManager.class).getBus().register(this);
        PictureManager pictureManager = ManagerFactory.getManagerService(PictureManager.class);
        if (bean.allowCrop && bean.maxCount == 1) { // 选择单张头像
            pictureManager.pickAvatar(context, bean, Constant.PictureConstants.PICTURE_PICKER);
        } else if (bean.maxCount > 0) {
            pictureManager.pickPhoto(context, bean, Constant.PictureConstants.PICTURE_PICKER);
        }
    }

    public void video(String json, Context context, JSCallback jsCallback) {
        if (!PermissionUtils.checkPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE)) {
            return;
        }
        mPickCallback = jsCallback;
        VideoBean bean = ManagerFactory.getManagerService(ParseManager.class).parseObject(json, VideoBean.class);
        ManagerFactory.getManagerService(DispatchEventManager.class).getBus().register(this);
        PictureManager pictureManager = ManagerFactory.getManagerService(PictureManager.class);
        pictureManager.openVideo(context, bean, Constant.PictureConstants.PICTURE_VIDEO);
    }

    public void camera(String json, Context context, JSCallback jsCallback) {
        if (!PermissionUtils.checkPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE)) {
            return;
        }
        mPickCallback = jsCallback;
        PictureBean bean = ManagerFactory.getManagerService(ParseManager.class).parseObject(json, PictureBean.class);
        ManagerFactory.getManagerService(DispatchEventManager.class).getBus().register(this);
        PictureManager pictureManager = ManagerFactory.getManagerService(PictureManager.class);
        pictureManager.openCamera(context, bean, Constant.PictureConstants.PICTURE_CAMERA);
    }

    public void qrcode(String json, Context context, JSCallback jsCallback) {
        QrcodeBean bean = ManagerFactory.getManagerService(ParseManager.class).parseObject(json, QrcodeBean.class);

        // 生成base64
        MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
        Map hints = new HashMap();
        //设置二维码四周白色区域的大小
        hints.put(EncodeHintType.MARGIN, 1);
        //设置二维码的容错性
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        int width = 400;
        int height = 400;
        if (bean.width != 0) {
            width = bean.width;
        }
        if (bean.height != 0) {
            height = bean.height;
        }

        String result = null;
        ByteArrayOutputStream baos = null;
        try {
            // 画二维码
            BitMatrix bitMatrix = multiFormatWriter.encode(bean.url, BarcodeFormat.QR_CODE, width, height, hints);
            BarcodeEncoder barcodeEncoder = new BarcodeEncoder();
            Bitmap bitmap = barcodeEncoder.createBitmap(bitMatrix);
            baos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);

            baos.flush();
            baos.close();

            byte[] bitmapBytes = baos.toByteArray();
            result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (WriterException e) {
            e.printStackTrace();
        } finally {
            try {
                if (baos != null) {
                    baos.flush();
                    baos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (jsCallback != null) {
            if (result != null && !TextUtils.isEmpty(result)) {
                JsPoster.postSuccess(result, jsCallback);
            } else {
                JsPoster.postFailed("生成二维码失败", jsCallback);
            }
        }
    }

    public void videoPreview(String json, Context context, JSCallback jsCallback) {
        mPickCallback = jsCallback;
        UploadImageBean bean = ManagerFactory.getManagerService(ParseManager.class).parseObject(json, UploadImageBean.class);
        ManagerFactory.getManagerService(DispatchEventManager.class).getBus().register(this);
        PictureManager pictureManager = ManagerFactory.getManagerService(PictureManager.class);
        pictureManager.videoPreview(context, bean);
    }

    @Subscribe
    public void OnUploadResult(UploadResultBean uploadResultBean) {
        if (uploadResultBean != null && mPickCallback != null) {
            JsPoster.postSuccess(uploadResultBean.data, mPickCallback);
        }

        ManagerFactory.getManagerService(DispatchEventManager.class).getBus().unregister(this);
        mPickCallback = null;
        ManagerFactory.getManagerService(PersistentManager.class).deleteCacheData(
            com.eros.framework.constant.Constant.ImageConstants.UPLOAD_IMAGE_BEAN);
    }

}
